package com.wxit.gulimall.order.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.PostConstruct;

/**
 * @author wj
 * @date
 * 2022.03.29 11:10
 */

@Configuration
public class MyRabbitConfig {

//    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 消费端确认(保证每一个消息被正确消费，此时才可以broker删除这个消息)
     *  1.默认是自动确认的，只要消息接收，客户端会自动确认，服务端就会移除这个消息
     *  产生问题：
     *      我们收到很多消息，自动回复给服务器ack,只有一个消息处理成功，宕机了，发生消息丢失，需要手动确认
     *      手动确认模式，只要我们没明确告诉MQ，货物被签收，没有ack,消息就一直是Unacked状态，即使consumer宕机，
     *      消息不会丢失，会重新变为Ready,下次发送给其他客户端
     */

//    @PostConstruct
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("correlationData ----" + correlationData + "====>" + ack + "----> " + cause);
        });

        /**
         * 设置消息抵达队列的确认回调
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("message---》" + message + "replyCode--->" + replyCode + "replyText--->" +replyText
             + "exchange--->" + exchange + "routingKey--->" + routingKey);
        });
    }

}
